package com.szzg10.webservice.chapter4;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class RabbitCounterServletClient {

	public static void main(String[] args) throws IOException {
		new RabbitCounterServletClient().doIt();
	}
	
	private void doIt() throws IOException {
		String address = "http://localhost:8080/szzg10/fib";
		
		//---POST---
		List<Integer> list = new ArrayList<Integer>();
		for(int i = 0; i < 10; i++) {
			list.add(i);
		}
		String payload = URLEncoder.encode("nums", "UTF-8") + "=" + URLEncoder.encode(list.toString(), "UTF-8");
		
		HttpURLConnection conn = getConnection(address, "POST");
		conn.setRequestProperty("accept", "text/xml");
		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		
		out.writeBytes(payload);
		out.flush();
		
		getResponse(conn);
		
		//---GET---
		conn = getConnection(address, "GET");
		conn.setRequestProperty("accept", "text/html");
		conn.connect();
		
		getResponse(conn);
		
		//---DELETE---
		conn = getConnection(address, "DELETE");
		conn.setRequestProperty("accept", "text/plain");
		conn.connect();
		
		getResponse(conn);
		
		//---POST---
		conn = getConnection(address, "POST");
		conn.setRequestProperty("accept", "text/xml");
		out = new DataOutputStream(conn.getOutputStream());
		
		out.writeBytes(payload);
		out.flush();
		
		getResponse(conn);
		
		//---GET---
		conn = getConnection(address, "GET");
		conn.setRequestProperty("accept", "text/html");
		conn.connect();
		
		getResponse(conn);
		
	}
	
	private HttpURLConnection getConnection(String address, String verb) throws IOException {
		URL url = new URL(address);
		
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setRequestMethod(verb);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		
		return conn;
	}
	
	private void getResponse(HttpURLConnection conn) throws IOException {
		String text = "";
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

		String next = "";
		while((next = reader.readLine()) != null) {
			text += next;
		}
		
		System.out.println(text);
		System.out.println();
	}
}
